package o2o.web.actions.mgnt;

import com.jinyou.utils.common.*;
import o2o.business.sms.JYSmsSeverBusiness;
import o2o.cache.order.OrderInfoMemory;
import o2o.cache.tip.TipInfoMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.config.dao.UserDaoSql;
import o2o.config.dao.utils.DaoUtils;
import o2o.config.dao.utils.Expression;
import o2o.config.dao.utils.QueryCondition;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.order.OrderInfo;
import o2o.dao.PO.suggest.SuggestInfo;
import o2o.dao.PO.tip.TipInfo;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.VO.SuggestVO;
import o2o.dao.VO.common.FileUploadInfo;
import o2o.service.order.OrderService;
import o2o.system.data.PROMPTS;
import o2o.system.data.SYS_CONFIG_PATH;
import o2o.utils.MultilingualResult;
import o2o.web.actions.user.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 类名称：SuggestAction
 * 类描述：  反馈意见管理
 */
@Controller
public class SuggestAction {
    //添加管理意见
    @RequestMapping(method = RequestMethod.POST, value = "/suggest/add")
    @ResponseBody
    public String suggest_add(String token, SuggestInfo info, FileUploadInfo fileUploadInfo, String lang) {
//		//如果token存在，则转换对应的人员
//		String username = "";
//		if(ValidateUtil.isNotNull(token)){
//			UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
//			if(user == null){
//				username = user.getUsername();
//			}
//		}
//
//		//添加反馈意见--调用服务添加
//		DubboNotify notify = DubboNotify.getInstance();
//		notify.setUsername(username).setStr01(suggest);
//		DubboService.getInstance().getSysSuggestService().addSysSuggest(notify);
//


//        String userKey = "";//用户账号（手机号或登录手机号）
//        UserInfo user = null;
//        if (ValidateUtil.isNotNull(token)) {
//            //token存在，则验证
//            user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
//            if (user == null) {
//                //存在token,证明已经登录
//                return AjaxResult.errorLogoutResult();
//            }
//            userKey = user.getUsername();
//        } else {
//            if (ValidateUtil.isNotMobile(info.getPhone())) {//验证是否为手机号
//                return AjaxResult.errorResult("请登录或者填写正确的联系方式");
//            }
//            userKey = info.getPhone();
//        }
        String userKey = "";//用户账号（手机号或登录手机号）
        UserInfo user = null;
        if (ValidateUtil.isNotNull(token)) {
            //token存在，则验证
            user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
            if (user == null) {
                //存在token,证明已经登录
//                return AjaxResult.errorLogoutResult();
            } else {
                userKey = user.getUsername();
            }
        } else {
//            if (ValidateUtil.isNotMobile(info.getPhone())) {//验证是否为手机号
//                return AjaxResult.errorResult("请登录或者填写正确的联系方式");
//            }
            userKey = info.getPhone();
        }
        // 如果是投诉的商家的话
        OrderInfo orderInfo = null;
        String str = "";
        // 如果是投诉的商家的话
        if (info.getType() == 2) {
            if (user == null) {
                return AjaxResult.errorLogoutResult();
            }
            if (ValidateUtil.isNull(info.getPhone())) {
                info.setPhone(user.getTelPhone());
            }
        } else if (info.getType() == SuggestInfo.SUGGEST_ORDER_TOUSU || info.getType() == SuggestInfo.SUGGEST_ORDER_SHOUHOU) {
            // 订单投诉
            if (user == null) {
                return AjaxResult.errorLogoutResult();
            }
            if (ValidateUtil.isNull(info.getPhone())) {
                info.setPhone(user.getTelPhone());
            }
            if (ValidateUtil.isID(info.getpId())) {
                SuggestInfo parentInfo_db = this.findByPId(info.getpId());
                if (parentInfo_db == null) {
                    return AjaxResult.errorResult("未获取到上级信息");
                }
                info.setShopId(parentInfo_db.getShopId());
                info.setOrderNo(parentInfo_db.getOrderNo());
                info.setBasicPId(ValidateUtil.isID(parentInfo_db.getBasicPId()) ? parentInfo_db.getBasicPId()
                        : parentInfo_db.getId());
                info.setUsername(user.getUsername());
            } else {
                orderInfo = OrderService.getInstance().findByOrderNo(info.getOrderNo());
                if (orderInfo == null) {
                    return AjaxResult.errorResult("未获取到订单信息");
                }
                if ((info.getType() == SuggestInfo.SUGGEST_ORDER_TOUSU && orderInfo.getIsApplyComplaint() != 0)
                        || (info.getType() == SuggestInfo.SUGGEST_ORDER_SHOUHOU && orderInfo.getIsApplyAfterSale() != 0)) {
                    return AjaxResult.errorResult("您已经申请过了,无需重复申请");
                }
                info.setUsername(user.getUsername());
                info.setOrderNo(orderInfo.getOrderNo());
                info.setShopId(orderInfo.getShopId());
                info.setCreateTim(DateUtils.getCurrTime());
                if (info.getTipId() != null) {
                    TipInfo tipInfo = TipInfoMemory.getInstance().getById(info.getTipId());
                    if (tipInfo != null) {
                        info.setTipName(tipInfo.getName());
                    }
                }
                if (info.getType() == SuggestInfo.SUGGEST_ORDER_TOUSU) {
                    str += "update " + PojoTables.OrderInfo + " set isApplyComplaint = 1 where orderNo ='" + orderInfo.getOrderNo() + "'";
                } else {
                    str += "update " + PojoTables.OrderInfo + " set isApplyAfterSale = 1 where orderNo ='" + orderInfo.getOrderNo() + "'";
                }
            }
        } else {
            if (ValidateUtil.isNull(info.getPhone())) {
                // 手机号空
                return AjaxResult.errorResult("手机号不能为空");
            } else if (info.getPhone().length() < 6) {
                return AjaxResult.errorResult("请输入正确的手机号");
            }
//            // 投诉建议
//            String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0,5-9]))\\d{8}$";
//            if (info.getPhone().length() != 11) {
//                return AjaxResult.errorResult("手机号应为11位数");
//            } else {
//                Pattern p = Pattern.compile(regex);
//                Matcher m = p.matcher(info.getPhone());
//                boolean isMatch = m.matches();
//                if (!isMatch) {
//                    return AjaxResult.errorResult("手机号格式不正确");
//                }
//            }
        }


        if (ValidateUtil.isNull(userKey)) {
            userKey = "匿名";
        }


        if (ValidateUtil.isNull(info.getContent())) {
            return AjaxResult.errorResult("请先填写意见");
        }

        if ("__vAutoTest121_".equalsIgnoreCase(info.getContent())) {
            return AjaxResult.errorResult("go");
        }

        info.setIsRead(0);
        Long time = DateUtils.getCurrTime();
        info.setCreateTim(time);
        if (ValidateUtil.isNull(info.getType())) {
            info.setType(SuggestInfo.SUGGEST);
        }
        info.setCreateUser(userKey);

        if (fileUploadInfo != null) {
            if (fileUploadInfo.getImage1() != null || ValidateUtil.isNotNull(fileUploadInfo.getBase64Img01())) {
                String filePath = fileUploadInfo.getImage1() != null ? JYImageUtils.saveImage(SYS_CONFIG_PATH.ORDER_IMAGE, fileUploadInfo.getImage1()) : JYImageUtils.saveImage(SYS_CONFIG_PATH.ORDER_IMAGE, fileUploadInfo.getBase64Img01());
                if (filePath == null) {
                    return MultilingualResult.errorResultV2(PROMPTS.FAILED_SAVE_IMG, lang);
                }
                info.setImage1Url(filePath);
            }
            if (fileUploadInfo.getImage2() != null || ValidateUtil.isNotNull(fileUploadInfo.getBase64Img02())) {
                String filePath = fileUploadInfo.getImage1() != null ? JYImageUtils.saveImage(SYS_CONFIG_PATH.ORDER_IMAGE, fileUploadInfo.getImage2()) : JYImageUtils.saveImage(SYS_CONFIG_PATH.ORDER_IMAGE, fileUploadInfo.getBase64Img02());
                if (filePath == null) {
                    return MultilingualResult.errorResultV2(PROMPTS.FAILED_SAVE_IMG, lang);
                }
                info.setImage2Url(filePath);
            }
            if (fileUploadInfo.getImage3() != null || ValidateUtil.isNotNull(fileUploadInfo.getBase64Img03())) {
                String filePath = fileUploadInfo.getImage1() != null ? JYImageUtils.saveImage(SYS_CONFIG_PATH.ORDER_IMAGE, fileUploadInfo.getImage3()) : JYImageUtils.saveImage(SYS_CONFIG_PATH.ORDER_IMAGE, fileUploadInfo.getBase64Img03());
                if (filePath == null) {
                    return MultilingualResult.errorResultV2(PROMPTS.FAILED_SAVE_IMG, lang);
                }
                info.setImage3Url(filePath);
            }
            if (fileUploadInfo.getImage4() != null || ValidateUtil.isNotNull(fileUploadInfo.getBase64Img04())) {
                String filePath = fileUploadInfo.getImage4() != null ? JYImageUtils.saveImage(SYS_CONFIG_PATH.ORDER_IMAGE, fileUploadInfo.getImage4()) : JYImageUtils.saveImage(SYS_CONFIG_PATH.ORDER_IMAGE, fileUploadInfo.getBase64Img04());
                if (filePath == null) {
                    return MultilingualResult.errorResultV2(PROMPTS.FAILED_SAVE_IMG, lang);
                }
                info.setImage4Url(filePath);
            }
        }

        try {
            UserDaoSql.getInstance().insertObj(PojoTables.SYS_SUGGEST, info);
            if (ValidateUtil.isNotID(info.getpId()) && (info.getType() == SuggestInfo.SUGGEST_ORDER_TOUSU || info.getType
                    () == SuggestInfo.SUGGEST_ORDER_SHOUHOU)) {
                UserDaoSql.getInstance().executeBySql(str);
                OrderInfoMemory.getInstance().modifyStatus(orderInfo.getOrderNo());
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("保存失败，请稍后再试");
        }

        return AjaxResult.successResult();
    }

    // 投诉建议/回复 形成对话
    @RequestMapping(method = RequestMethod.POST, value = "/manager/suggest/reply")
    @ResponseBody
    public String suggest_reply(String token, String sysAppKey, SuggestInfo info, FileUploadInfo fileUploadInfo,
                                String lang) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (info.getType() == SuggestInfo.SUGGEST_ORDER_TOUSU || info.getType() == SuggestInfo.SUGGEST_ORDER_SHOUHOU) {
            if (ValidateUtil.isNotID(info.getpId())) {
                return AjaxResult.errorResult("上级id不正确");
            }
            if (ValidateUtil.isNotID(info.getBasicPId())) {
                info.setBasicPId(info.getpId());
            }
            SuggestInfo parentInfo_db = this.findByPId(info.getBasicPId());
            if (parentInfo_db == null) {
                return AjaxResult.errorResult("未获取到上级信息");
            }
            info.setShopId(parentInfo_db.getShopId());
            info.setOrderNo(parentInfo_db.getOrderNo());
            info.setCreateTim(DateUtils.getCurrTime());
            info.setUsername(user.getUsername());
            info.setName(user.getName());
            info.setUserCategory(2);
            info.setCreateUser(user.getUsername());
            if (fileUploadInfo != null) {
                if (fileUploadInfo.getImage1() != null || ValidateUtil.isNotNull(fileUploadInfo.getBase64Img01())) {
                    String filePath = fileUploadInfo.getImage1() != null ? JYImageUtils.saveImage(SYS_CONFIG_PATH.ORDER_IMAGE, fileUploadInfo.getImage1()) : JYImageUtils.saveImage(SYS_CONFIG_PATH.ORDER_IMAGE, fileUploadInfo.getBase64Img01());
                    if (filePath == null) {
                        return MultilingualResult.errorResultV2(PROMPTS.FAILED_SAVE_IMG, lang);
                    }
                    info.setImage1Url(filePath);
                }
                if (fileUploadInfo.getImage2() != null || ValidateUtil.isNotNull(fileUploadInfo.getBase64Img02())) {
                    String filePath = fileUploadInfo.getImage1() != null ? JYImageUtils.saveImage(SYS_CONFIG_PATH.ORDER_IMAGE, fileUploadInfo.getImage2()) : JYImageUtils.saveImage(SYS_CONFIG_PATH.ORDER_IMAGE, fileUploadInfo.getBase64Img02());
                    if (filePath == null) {
                        return MultilingualResult.errorResultV2(PROMPTS.FAILED_SAVE_IMG, lang);
                    }
                    info.setImage2Url(filePath);
                }
                if (fileUploadInfo.getImage3() != null || ValidateUtil.isNotNull(fileUploadInfo.getBase64Img03())) {
                    String filePath = fileUploadInfo.getImage1() != null ? JYImageUtils.saveImage(SYS_CONFIG_PATH.ORDER_IMAGE, fileUploadInfo.getImage3()) : JYImageUtils.saveImage(SYS_CONFIG_PATH.ORDER_IMAGE, fileUploadInfo.getBase64Img03());
                    if (filePath == null) {
                        return MultilingualResult.errorResultV2(PROMPTS.FAILED_SAVE_IMG, lang);
                    }
                    info.setImage3Url(filePath);
                }
                if (fileUploadInfo.getImage4() != null || ValidateUtil.isNotNull(fileUploadInfo.getBase64Img04())) {
                    String filePath = fileUploadInfo.getImage4() != null ? JYImageUtils.saveImage(SYS_CONFIG_PATH.ORDER_IMAGE, fileUploadInfo.getImage4()) : JYImageUtils.saveImage(SYS_CONFIG_PATH.ORDER_IMAGE, fileUploadInfo.getBase64Img04());
                    if (filePath == null) {
                        return MultilingualResult.errorResultV2(PROMPTS.FAILED_SAVE_IMG, lang);
                    }
                    info.setImage4Url(filePath);
                }
            }
            try {
                UserDaoSql.getInstance().insertObj(PojoTables.SYS_SUGGEST, info);
                if (info.getState() != parentInfo_db.getState()) {
                    StringBuffer sql = new StringBuffer();
                    sql.append(" update ").append(PojoTables.SYS_SUGGEST).append(" set state =").append(info.getState())
                            .append(", updateUser = '").append(user.getUsername()).append("'")
                            .append(" where (id = ").append(info.getBasicPId()).append(" or basicPId = ").append(info.getBasicPId()).append(")")
                            .append(" and delFlag = 0");
                    UserDaoSql.getInstance().executeBySql(sql.toString());
                }
            } catch (SQLException e) {
                e.printStackTrace();
                return AjaxResult.errorResult("保存失败，请稍后再试");
            }
        }
        return AjaxResult.successResult();
    }

    // 获取投诉建议列表
    @RequestMapping(method = RequestMethod.POST, value = "/manager/suggest/search")
    @ResponseBody
    public String find_suggest_search(String token, String orderNo, Long shopId, Integer type, Long startTime, Long
            endTime, Long tipId, Integer state, Integer page, Integer size) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (page == null) {
            page = 1;
        }
        if (size == null) {
            size = 1;
        }
        String sql = " select sg.* from " + PojoTables.SYS_SUGGEST + " as sg ";
        String whereSql = "" + " where sg.delFlag = 0 and  sg.pId = 0";
        if (ValidateUtil.isNotNull(orderNo)) {
            whereSql += " and sg.orderNo like '%" + orderNo + "%' ";
        }
        if (type != null) {
            whereSql += " and sg.type =" + type + " ";
        }
        if (ValidateUtil.isID(shopId)) {
            whereSql += " and sg.shopId =" + shopId + " ";
        }
        if (ValidateUtil.isID(tipId)) {
            whereSql += " and sg.tipId =" + tipId + " ";
        }
        if (state != null) {
            whereSql += " and sg.state =" + state + " ";
        }
        if (ValidateUtil.isAbsLong(startTime)) {
            whereSql += " and sg.createTim >" + startTime + " ";
        }
        if (ValidateUtil.isAbsLong(endTime)) {
            whereSql += " and sg.createTim <" + endTime + " ";
        }
        long count = 0;
        String countSQL = "select count(1) as counts from " + PojoTables.SYS_SUGGEST + " as sg ";
        String limit = " order by sg.id desc limit " + (page - 1) * size + "," + size;
        List<SuggestVO> list = null;
        try {
            count = UserDaoSql.getInstance().getCount(countSQL + whereSql);
            list = (List<SuggestVO>) UserDaoSql.getInstance().list(SuggestVO.class, sql + whereSql + limit);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult(e.getMessage());
        }
        if (ValidateUtil.isAbsList(list)) {
            for (SuggestVO vo : list) {
                conver(vo);
            }
            return AjaxResult.successResult(list, count);
        }
        return AjaxResult.successResult(null, 0);
    }

    // 处理
    private void conver(SuggestVO vo) {
        if (vo != null) {
            UserInfo userInfo = UserInfoMemory.getInstance().getUserInfo(vo.getUsername());
            if (userInfo != null) {
                vo.setName(userInfo.getName());
            }
            // 图片处理
            if (ValidateUtil.isNotNull(vo.getImage1Url()) && ValidateUtil.isNotNetUrl(vo.getImage1Url())) {
                vo.setImage1Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + vo.getImage1Url());
            }
            if (ValidateUtil.isNotNull(vo.getImage2Url()) && ValidateUtil.isNotNetUrl(vo.getImage2Url())) {
                vo.setImage1Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + vo.getImage2Url());
            }
            if (ValidateUtil.isNotNull(vo.getImage3Url()) && ValidateUtil.isNotNetUrl(vo.getImage3Url())) {
                vo.setImage1Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + vo.getImage3Url());
            }
            if (ValidateUtil.isNotNull(vo.getImage4Url()) && ValidateUtil.isNotNetUrl(vo.getImage4Url())) {
                vo.setImage1Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + vo.getImage4Url());
            }
        }
    }

    // 根绝订单获取投诉
    @RequestMapping({"/manager/suggest/by/orderNo", "/user/suggest/by/orderNo"})
    @ResponseBody
    public String list_suggest_by_orderNo(String token, String orderNo, Integer type) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (ValidateUtil.isNull(orderNo)) {
            return AjaxResult.errorResult("订单号不能为空");
        }
        if (type == null) {
            return AjaxResult.errorResult("类型不能为空");
        }

        String sql = "select sg.*,si.shopName as shopName from " + PojoTables.SYS_SUGGEST + " as sg "
                + " left join " + PojoTables.ShopInfo + " as si on sg.shopId = si.id "
                + " where sg.delFlag = 0  and sg.type = " + type
                + " and sg.orderNo ='" + orderNo + "'";


        List<SuggestVO> list = null;
        try {
            list = (List<SuggestVO>) UserDaoSql.getInstance().list(SuggestVO.class, sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (ValidateUtil.isAbsList(list)) {
            for (SuggestVO vo : list) {
                conver(vo);
            }
            return AjaxResult.successResult(list.size(), list);
        }
        return AjaxResult.successResult(0, null);
    }

    // 用户获取投诉/售后
    @RequestMapping("/user/suggest/list")
    @ResponseBody
    public String list_suggest_by_orderNo(String token, Integer type, Integer page, Integer size) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (type == null) {
            return AjaxResult.errorResult("类型不能为空");
        }
        if (page == null) {
            page = 1;
        }
        if (size == null) {
            size = 20;
        }

        String sql = "select sg.*,si.shopName as shopName from " + PojoTables.SYS_SUGGEST + " as sg "
                + " left join " + PojoTables.ShopInfo + " as si on sg.shopId = si.id "
                + " where sg.delFlag = 0  and sg.type = " + type + " and sg.pId = 0 order By id desc limit " + (page
                - 1)
                * size + "," + size;
        String countSql = "select count(1) as counts from " + PojoTables.SYS_SUGGEST + " WHERE delFlag = 0 and type " +
                "=" + type + " and pId = 0";
        List<SuggestVO> list = null;
        long count = 0;
        try {
            count = UserDaoSql.getInstance().getCount(countSql.toString());
            list = (List<SuggestVO>) UserDaoSql.getInstance().list(SuggestVO.class, sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (ValidateUtil.isAbsList(list)) {
            for (SuggestVO vo : list) {
                conver(vo);
            }
            return AjaxResult.successResult(list, count);
        }
        return AjaxResult.successResult(null, count);
    }

    // 根绝id获取信息
    private SuggestInfo findByPId(Long pId) {
        if (pId == null) {
            return null;
        }
        //数据库中查
        QueryCondition query = QueryCondition.getInstance();
        Expression expression = Expression.getInstance();
        expression.addChild("delFlag", 0);//未删除
        expression.addChild("id", pId);
        query.addCondition(expression);
        String sql = DaoUtils.getSql(PojoTables.SYS_SUGGEST, query);
        SuggestInfo info = null;
        try {
            info = (SuggestInfo) UserDaoSql.getInstance().getObject(SuggestInfo.class, sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return info;
    }

    //获取意见管理列表
    @RequestMapping(method = RequestMethod.POST, value = "/admin/suggest/list")
    @ResponseBody
    public String suggest_list(String token, Integer isRead, Long shopId, Integer type, String phone, Long startTime, Long endTime, Integer page, Integer size) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        // if (!User.hasSuperAdminAuth(user.getUserType())) {
        //     return AjaxResult.errorResult("您没有权限");
        // }

        if (ValidateUtil.isNotAbsInteger(page)) {
            page = 1;
        }
        if (ValidateUtil.isNotAbsInteger(size)) {
            size = 20;
        }


//        QueryCondition query = QueryCondition.getInstance();
//        Expression expression = Expression.getInstance();
//        expression.addChild("delFlag", 0);//所有未删除的店铺
//
//        if (ValidateUtil.isAbsInteger(type)) {
//            expression.addChild("type", type);
//        }
////        if (ValidateUtil.isAbsInteger(type)) {
////            switch (type) {
////                case SUGGEST: {//意见反馈
////                    expression.addChild("type", type);
////                }
////                break;
////                case SUGGEST_TOUSU: {//投诉
////                    expression.addChild("type", type);
////                }
////                break;
////                case ALL: {//全部
////                }
////                break;
////            }
////        }
//        if (ValidateUtil.isAbsInteger(isRead)) {
//            switch (isRead) {
//                case 1: {//已读
//                    expression.addChild("isRead", 1);
//                }
//                break;
//                case 2: {//未读
//                    expression.addChild("isRead", 0);
//                }
//                break;
//                case 3: {//全部
//                }
//                break;
//            }
//        }
//        if (ValidateUtil.isNotNull(phone)) {
//            expression.addChild("phone", "like", phone);
//        }
//        if (null != startTime) {
//            expression.addChild("createTim", ">=", startTime);
//        }
//        if (null != endTime) {
//            expression.addChild("createTim", "<=", endTime);
//        }
//        query.addCondition(expression);
//        query.setPage(page);
//        query.setSize(size);
//        String sql = DaoUtils.getSql(PojoTables.SYS_SUGGEST, query);
//        String sqlCount = DaoUtils.getSqlCount(PojoTables.SYS_SUGGEST, query);
//        List<SuggestInfo> list = null;
//        Long count = 0l;
//        try {
//            list = (List<SuggestInfo>) UserDaoSql.getInstance().list(SuggestInfo.class, sql);
//            count = UserDaoSql.getInstance().getCount(sqlCount);
//        } catch (SQLException e) {
//            e.printStackTrace();
//            return AjaxResult.errorResult("获取失败，请稍后再试");
//        }
        StringBuilder sql = new StringBuilder();
        sql.append(" select * ").append(" from ").append(PojoTables.SYS_SUGGEST)
                .append(" where delFlag = 0 ");
        if (ValidateUtil.isAbsInteger(type)) {
            sql.append(" and type = ").append(type);
        }
        if (ValidateUtil.isAbsInteger(isRead)) {
            switch (isRead) {
                case 1: {//已读
                    sql.append(" and isRead = ").append(1);
                }
                break;
                case 2: {//未读
                    sql.append(" and isRead = ").append(0);
                }
                break;
                case 3: {//全部
                }
                break;
            }
        }
        if (ValidateUtil.isNotNull(phone)) {
            sql.append(" and  phone like '%").append(phone).append("%'");
        }
        if (ValidateUtil.isID(shopId)) {
            sql.append(" and  shopId  =").append(shopId);
        }
        if (null != startTime) {
            sql.append(" and  createTim >= ").append(startTime).append("");
        }
        if (null != endTime) {
            sql.append(" and  createTim <= ").append(endTime).append("");
        }
        sql.append(" order by createTim desc ");
        List<SuggestInfo> list_db = null;
        try {
            list_db = (List<SuggestInfo>) UserDaoSql.getInstance().list(SuggestInfo.class, sql.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("获取失败，请稍后再试");
        }
        if (!ValidateUtil.isAbsList(list_db)) {
            return AjaxResult.successResult(null, 0);
        }
        JYPageUtils.PageList pageList = JYPageUtils.getList(list_db, page, size);
        List<SuggestInfo> list = (List<SuggestInfo>) pageList.list;
        if (null != list && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                if (null == list.get(i)) {
                    continue;
                }
                // 图片1
                if (ValidateUtil.isNotNull(list.get(i).getImage1Url())) {
                    if (ValidateUtil.isNotNetUrl(list.get(i).getImage1Url())) {
                        list.get(i).setImage1Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + list.get(i).getImage1Url());
                    }
                }
                // 图片2
                if (ValidateUtil.isNotNull(list.get(i).getImage2Url())) {
                    if (ValidateUtil.isNotNetUrl(list.get(i).getImage2Url())) {
                        list.get(i).setImage2Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + list.get(i).getImage2Url());
                    }
                }
                // 图片3
                if (ValidateUtil.isNotNull(list.get(i).getImage3Url())) {
                    if (ValidateUtil.isNotNetUrl(list.get(i).getImage3Url())) {
                        list.get(i).setImage3Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + list.get(i).getImage3Url());
                    }
                }
                // 图片4
                if (ValidateUtil.isNotNull(list.get(i).getImage4Url())) {
                    if (ValidateUtil.isNotNetUrl(list.get(i).getImage4Url())) {
                        list.get(i).setImage4Url(SYS_CONFIG_PATH.IMAGE_BASE_URL + list.get(i).getImage4Url());
                    }
                }
            }
        }
        return AjaxResult.successResult(list, pageList.totalCount);
    }

    //标记为已读
    @RequestMapping(method = RequestMethod.POST, value = "/admin/suggest/setread")
    @ResponseBody
    public String suggest_set_read(String token, String ids, String reply) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasSuperAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有权限");
        }

        if (ValidateUtil.isNull(ids)) {
            return AjaxResult.errorResult("请选择要标记的");
        }
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.SYS_SUGGEST).append(" set isRead = 1");
        if (ValidateUtil.isNotNull(reply)) {
            sb.append(",replyContent ='").append(reply).append("'");
        }
        sb.append(",updateUser = '").append(user.getUsername())
                .append("' where delFlag = 0 and id in (").append(ids).append(")");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("标记失败，请稍后再试");
        }
        return AjaxResult.successResult();
    }

    // 处理售后 /投诉
    @RequestMapping(method = RequestMethod.POST, value = "/admin/suggest/deal")
    @ResponseBody
    public String suggest_deal(String token, Long id, String reply) {
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        // if (!User.hasSuperAdminAuth(user.getUserType())) {
        //     return AjaxResult.errorResult("您没有权限");
        // }
        // query
        QueryCondition query = QueryCondition.getInstance();
        Expression expression = Expression.getInstance();
        expression.addChild("delFlag", 0);
        expression.addChild("id", id);
        query.addCondition(expression);
        String querySql = DaoUtils.getSql(PojoTables.SYS_SUGGEST, query);
        SuggestInfo info = null;
        try {
            info = (SuggestInfo) UserDaoSql.getInstance().list(SuggestInfo.class, querySql.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (info == null) {
            return AjaxResult.errorResult("未获取到信息");
        }
        StringBuilder sb = new StringBuilder();
        sb.append("update ").append(PojoTables.SYS_SUGGEST).append(" set isRead = 1");
        if (ValidateUtil.isNotNull(reply)) {
            sb.append(",replyContent ='").append(reply).append("'");
        }
        sb.append(",updateUser = '").append(user.getUsername())
                .append("' where delFlag = 0 and id =").append(id).append("");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
            if (info.getType() == SuggestInfo.SUGGEST_ORDER_TOUSU || info.getType() == SuggestInfo.SUGGEST_ORDER_SHOUHOU) {
                String str = "";
                if (info.getType() == SuggestInfo.SUGGEST_ORDER_TOUSU) {
                    str += "update " + PojoTables.OrderInfo + " set isApplyComplaint = 2 where orderNo ='" + info.getOrderNo() + "'";
                } else {
                    str += "update " + PojoTables.OrderInfo + " set isApplyAfterSale = 2 where orderNo ='" + info.getOrderNo() + "'";
                }
                UserDaoSql.getInstance().executeBySql(str);
                OrderInfoMemory.getInstance().modifyStatus(info.getOrderNo());
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("标记失败，请稍后再试");
        }
        return AjaxResult.successResult();
    }


}
